package cn.tedu.micro.demo.controller;

import cn.tedu.micro.demo.amqp.AmqpProducer;
import cn.tedu.micro.demo.pojo.MessagePO;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class SendController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpProducer<MessagePO> amqpProducer;
    @GetMapping("/send")
    public String send(String msg){
        //消息包含消息体 消息头 消息路由key
        MessageProperties props=new MessageProperties();
        props.setExpiration("50000");
        Message message=new Message(msg.getBytes(),props);
        //调用rabbitTemplate方法 发送消息
        rabbitTemplate.convertAndSend("demo_ex","demo_rk",message);
        return "发送成功";
    }
    @GetMapping("/send/msg")
    public String send(MessagePO msg){
        MessageProperties props=new MessageProperties();
        props.setExpiration("50000");
        Message message=new Message(searializer(msg),props);
        rabbitTemplate.convertAndSend("demo_ex","demo_rk",message);
        return "发送成功";
    }
    @GetMapping("/send/po")
    public String sendPO(MessagePO po){
        amqpProducer.send("demo_ex","demo_rk",po,50000L);
        return "发送成功";
    }
    public byte[] searializer(MessagePO msg){
        //1. 对象转化成json
        String msgJson = JSON.toJSONString(msg);
        log.info("发送的消息为：{}",msgJson);
        //2. json字符串转化成字节数组
        return msgJson.getBytes();
    }
}
